package zhongbo.java.air.fightpath.service.Impl;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import zhongbo.java.air.fightpath.listener.RedisPathChanelPublisher;
import zhongbo.java.air.fightpath.mapper.FlightMapper;
import zhongbo.java.air.fightpath.model.FlightPath;

import java.util.Date;

@Service
@Slf4j
public class PathServiceImpl {
    @Autowired
    private FlightMapper flightMapper;

    @Autowired
    private RedisPathChanelPublisher publisher;

    public FlightPath add(FlightPath flightPath) {
        String type = flightPath.getSourceType();
        if (StrUtil.isBlank(type)) {
            type = "";
        }
        flightPath.setSourceType(type); // 更新 sourceType 字段
        flightMapper.insert(flightPath);
        log.info("航迹入数据库: {}", flightPath);
        //广播到live_flight_path频
        publisher.sendMessageJson(flightPath);
        return flightPath;
    }

    public void processMessage(String msgString) {
        try {
            JSONObject jsonObject = JSONUtil.parseObj(msgString);
            FlightPath flightPath = new FlightPath();

            flightPath.setIcaoCode(jsonObject.getStr("icaoCode"));
            //    flightPath.setTimestamp(jsonObject.getDate("timestamp"));---->可能导致出错：
            //    jsonObject.getDate("timestamp") 会直接将时间戳转换为 Date 对象。
            // 但这种方式可能会导致问题，因为如果时间戳值无效，Date 对象可能会生成一个不合法的日期时间值。
            // 获取时间戳
            Long timestamp = jsonObject.getLong("timestamp");
            if (timestamp != null) {
                // 检查时间戳是否在 MySQL 的支持范围内
                if (timestamp >= 1000L * 365 * 24 * 60 * 60 * 1000 && timestamp <= 9999L * 365 * 24 * 60 * 60 * 1000) {
                    Date date = new Date(timestamp);
                    flightPath.setTimestamp(date);
                } else {
                    // 如果超出范围，设置为当前时间
                    Date currentDate = new Date();
                    flightPath.setTimestamp(currentDate);
                }
            } else {
                // 如果时间戳为空，设置为当前时间
                Date currentDate = new Date();
                flightPath.setTimestamp(currentDate);
            }
            flightPath.setLatitude(jsonObject.getDouble("latitude"));
            flightPath.setLongitude(jsonObject.getDouble("longitude"));
            flightPath.setAltitude(jsonObject.getDouble("altitude"));
            flightPath.setSpeed(jsonObject.getDouble("speed"));
            flightPath.setHeading(jsonObject.getDouble("heading"));
            flightPath.setSourceType(jsonObject.getStr("sourceType"));

            add(flightPath);
        } catch (Exception e) {
            log.error("Error processing message: {}", msgString, e);
        }
    }
}

